<template>
    <div style="display:flex;">
        <!-- 个人信息卡片 -->
        <el-card>
            <el-descriptions class="margin-top" title="个人信息" :column="1" size="medium" style="width:300px;font-size:16px">
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-picture-outline" style="line-height:178px"></i>
                        头像
                    </template>
                    <div>
                        <el-upload
                            class="avatar-uploader boxCardUploadImg "
                            action="/img-api/img/upload/avatar"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :headers="headers"
                            name="file"
                            :before-upload="beforeAvatarUpload"
                            :on-progress="uploadAvatarProcess">
                            <img v-if="'/imgs/avatar/'+userInfo.avatar" :src="'/imgs/avatar/'+userInfo.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <i class="el-icon-edit" ></i>
                            </el-upload>
                        <el-progress :style="progressStyle" :text-inside="true" :stroke-width="16" :percentage="loadProgress" :status="progressStatus"></el-progress>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item >
                    <template slot="label">
                        <i class="el-icon-user"></i>
                        用户名
                    </template>
                    {{ userInfo.username }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        手机号
                    </template>
                    {{ userInfo.mobile?userInfo.mobile:'未知' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-office-building"></i>
                        联系地址
                    </template>
                        {{ userInfo.address?userInfo.address:'未知' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-present"></i>
                        生日
                    </template>
                        {{ userInfo.birthday?userInfo.birthday:'未知' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-connection"></i>
                        性别
                    </template>
                        {{ userInfo.sex?userInfo.sex:'未知' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-s-custom"></i>
                        身份权限
                    </template>
                        {{ userInfo.role }}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-card style="margin-left:20px">
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane label="基本资料" name="baseInfo" style="width:800px">
                    <el-form :model="userInfo" :inline="true" label-width="100px" :rules='rules' ref="userInfo">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="用户名" prop="username">
                                    <el-input type="text" placeholder="请输入用户名" v-model="userInfo.username"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="联系电话" prop="mobile">
                                    <el-input type="text" placeholder="请输入联系电话" v-model="userInfo.mobile"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="性 别" prop="sex">
                                    <el-select v-model="userInfo.sex" placeholder="请选择">
                                        <el-option v-for="(item,index) in sexList" :key="'sex-'+index" :value="item" :label="item"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="生 日" prop="birthday">
                                    <el-date-picker value-format="yyyy-MM-dd" type="date" v-model="userInfo.birthday"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="身份权限" prop="role">
                                    <el-select v-model="userInfo.role" placeholder="请选择">
                                        <el-option value="SUPER_ADMIN" label="超级管理员"></el-option>
                                        <el-option value="ADMIN" label="管理员"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="住址" prop="address">
                                    <el-input type="text" placeholder="请输入住址" v-model="userInfo.address"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="" prop="operate">
                                    <el-button type="primary" @click="handleSubmit" style="margin-left:80px">保存</el-button>
                                    <el-button @click="handleReset">重置</el-button>
                               </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="changePassword" style="width:800px">
                    <el-form :model="passwordInfo" :inline="true" label-width="100px" :rules='rules' ref="passwordInfo">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="旧密码" prop="oldPassword">
                                    <el-input type="password" placeholder="请输入旧密码" v-model="passwordInfo.oldPassword"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="新密码" prop="password">
                                    <el-input type="password" placeholder="请输入新密码" v-model="passwordInfo.password"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="确认新密码" prop="confirmPassword">
                                    <el-input type="password" placeholder="请确认新密码" v-model="passwordInfo.confirmPassword"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="" prop="operate">
                                    <el-button type="primary" @click="handleSubmit" style="margin-left:80px">保存</el-button>
                                    <el-button @click="handleReset">重置</el-button>
                               </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script>
    import { getUser,updateUser,updatePassword } from '@/api/user'
    export default {
        name: 'Profile',
        data(){
            //检查密码是否合法
            const checkPassword = (rule,value,callback)=>{
                //要求存在内容且长度必须在6-16位
                if (value.length > 16 || value.length < 6){
                    return callback(new Error('长度必须在6-16之间'))
                }
                if (value.length > 16 || value.length < 6){
                    return callback(new Error('长度必须在6-16之间'))
                }
                callback()
            }
            //检查密码输入是否一致
            const checkConfirmPassword = (rule,value,callback)=>{
                //要求存在内容且长度必须在6-16位
                if (this.passwordInfo.password != value){
                    return callback(new Error('密码不一致，请重新确认'))
                }
                callback()
            }
            //检查联系电话是否合法
            const checkMobile = (rule,value,callback)=>{
                //不设置时通过
                if(!value){
                    return callback()
                }
                //设置时需要符合正则表达式则为合法联系电话
                let reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
                if(!reg.test(value)){
                    return callback(new Error('请输入合法联系电话'))
                }
                callback()
            }
            return{
                userInfo:{avatar:'default.jpg'},
                passwordInfo:{oldPassword:'',password:'',confirmPassword:''},
                fileName:null,
                headers:{
                    Authorization: 'Bearer ' + this.$Cookie.get('login-token')
                },
                loadProgress: 0,
                progressStatus:null,
                progressStyle: "margin-top:5px;opacity: 0;",
                activeName: 'baseInfo',
                sexList:['男','女','未知'],
                unitList:[],
                unit:0,
                rules:{
                    username:[
                        {required:true,message:'请输入用户名',trigger:'blur'},
                        {min:5,max:16,message:'长度必须在5-16之间',trigger:'blur'}
                    ],
                    mobile:[
                        {validator:checkMobile,trigger:'blur'},
                    ],
                    oldPassword:[
                        {required:true,message:'请输入旧密码',trigger:'blur'},
                        {validator:checkPassword,trigger:'blur'}
                    ],
                    password:[
                        {required:true,message:'请输入新密码',trigger:'blur'},
                        {validator:checkPassword,trigger:'blur'}
                    ],
                    confirmPassword:[
                        {required:true,message:'请确认新密码',trigger:'blur'},
                        {validator:checkConfirmPassword,trigger:'blur'}
                    ],
                },
            }
        },
        //页面初始化调用
        created(){
            this.getUserInfo()
        },
        methods:{
            //获取用户信息
            getUserInfo(){
                //调用接口获取登录用户信息
                getUser(this.$Cookie.get("userId")).then(res=>{this.userInfo = res.data})
                
            },
            
            //调用接口更新数据
            handleSubmit(){
                if(this.passwordInfo.password){  //如果新密码存在则认为在修改密码
                    this.$refs['passwordInfo'].validate((valid)=>{
                        if(valid){
                            this.userInfo.updateBy = this.$Cookie.get("username")
                            this.userInfo.oldPassword = this.passwordInfo.oldPassword
                            this.userInfo.password = this.passwordInfo.password
                            updatePassword(this.userInfo).then(res=>{
                                this.$Cookie.remove('login-token')
                                this.$Cookie.remove('username')
                                this.$Cookie.remove('userId')
                                this.$router.replace('/login')
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                    })
                }else{ //新密码不存在则认为在修改基础资料
                    this.$refs['userInfo'].validate((valid)=>{
                        if(valid){
                            this.userInfo.updateBy = this.$Cookie.get("username")
                            updateUser(this.userInfo).then(res=>{
                                window.location = window.location
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                    })
                }
            },
            //将数据恢复
            handleReset(){
                this.passwordInfo.password = ''
                this.passwordInfo.confirmPassword = ''
                this.getUserInfo()
            },
            //头像上传前调用函数
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //上传头像进度
            uploadAvatarProcess(event, file, fileList) {
                this.progressStyle="margin-top:5px;opacity: 1;",
                this.loadProgress = parseInt(event.percent);
                if (this.loadProgress >= 100) {
                    this.progressStatus = "success"
                    this.loadProgress = 100
                    setTimeout( () => {this.progressStyle="margin-top:5px;opacity: 0;";this.progressStatus = null}, 1000) 
                }
            },
            //头像上传成功调用函数,更新数据
            handleAvatarSuccess(res, file) {
                this.fileName = res.data
                this.userInfo.avatar = this.fileName;
            },
            //标签页点击
            handleClick(tab, event) {
                if(event.target.innerText == '修改密码'){
                    this.handleReset()
                }else{
                    this.passwordInfo.password = ''
                    this.handleReset()
                }
            }
        }
    }
</script>

<style scoped>
    .address-form .el-select .el-input {
        border-color: #409EFF;
        width: 50px;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 20px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    border-radius: 20px;
    display: block;
  }
  
.boxCardUploadImg {
  width: 178px;
  height: 178px;
  border-radius: 20px;

  position: relative;
}
.boxCardUploadImg:hover {
  cursor: pointer;
}
.boxCardUploadImg:hover::after {
  content: '';
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 0;
  height: 100%;
  top: 0px;
  width: 100%;
  z-index: 99;
  border-radius: 20px;
}

.boxCardUploadImg i {
  display: none;
}
.boxCardUploadImg:hover i {
  position: absolute;
  font-size: 48px;
  display: initial;
  z-index: 999;
  color: #fff;
  
  top: 65px;
  left: 65px;
}
</style>